<template>
  <div class="container">
    <main-header :actived="3"/>
    <!-- <img class="share-loading" v-if="!loaded" src='../../assets/img/logo-b.png' /> -->
    <!-- 产品分类 -->
    <div class="product-tabs" v-if="action !== 'you'">
      <div class="tabs-list">
        <div 
          class="item" 
          :class="{'item-cur': curIndex === index}" 
          v-for="(item, index) in categories" 
          :key="index"
          @click="itemClicked(index)"
        >
          <span>{{item}}</span>
        </div>
      </div>
      <router-link to="/lifePub" class="pub">上传</router-link>
    </div>
    <div class="me you" v-if="curIndex !== 2 && waterfallList1.length && action === 'you'">
      <img class="avatar" v-if="waterfallList1[0].MemberPhoto==='' || waterfallList1[0].MemberPhoto===null" src='../../assets/img/person.png' />
      <img class="avatar" v-else :src='waterfallList1[0].MemberPhoto' />

      <div class="user-info">
        <div class="name">
          <em>{{waterfallList1[0].MemberName}}</em>
          <span v-if="youISP">TITIKA城市运营商</span>
          <span v-else-if="youBelongMan">TITIKA签约品牌主理人</span>
        </div>
        <div class="counts">
          <!-- <span>关注 {{FollowedCount}}</span> -->
          <span>关注 {{FollowCount}}</span>
          <!-- <span>粉丝 {{Subordinate}}</span> -->
          <span>粉丝 {{FollowedCount}}</span>
          <span>点赞 {{AllThemeZans}}</span>
        </div>
      </div>
      <div class="concern" @click.stop="followUser" v-if="!isMine">
        <span v-if="isFollow">取消关注</span>
        <img v-else src='../../assets/img/icon-concern.png' />
      </div>
    </div>
    <div class="me" v-if="curIndex === 2">
      <img v-if="userPhoto==='' || userPhoto===null" class="avatar" src='../../assets/img/person.png' />
      <img v-else class="avatar" :src='userPhoto' />
      <div class="user-info">
        <div class="name">
          <em>{{userNick}}</em>
          <span v-if="isBelongMan">TITIKA签约品牌主理人</span>
        </div>
        <div class="counts">
          <span>关注 {{FollowCount}}</span>
          <span>粉丝 {{FollowedCount}}</span>
          <span>点赞 {{AllThemeZans}}</span>
        </div>
      </div>
      <div class="share" v-if="isBelongMan" id="copyBtn">
        <img src='../../assets/img/share.png' />
      </div>
    </div>
    <div class="v-waterfall-content" id="v-waterfall">
      <div class="item-col">
        <!-- 'max-height': loaded?'1000px':'10px',  -->
        <div v-for="(item, index) in waterfallList1"
          :key="index"
          class="v-waterfall-item"
          :style="{'opacity': loaded?'1':'0'}"
          @click="goToDetail(item.Id)"
        >
          <img :src="item.ImagePath[0]" />
          <div class="detail">
            <div class="say">
              {{item.ShortDescription}}
            </div>
            <div class="user">
              <div class="userhd">
                <img v-if="item.MemberPhoto==='' || item.MemberPhoto===null" src='../../assets/img/person.png' />
                <img v-else :src='item.MemberPhoto' />
              </div>
              <div class="person">{{item.MemberName}}</div>
              <!-- @click.stop="like(item.Id)" -->
              <div class="good">
                <img src='../../assets/img/good.png' />
                <i>{{item.ZanCounts}}</i>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="item-col">
        <div v-for="(item, index) in waterfallList2"
          :key="index"
          class="v-waterfall-item"
          :style="{'opacity': loaded?'1':'0'}"
          @click="goToDetail(item.Id)"
        >
          <img :src="item.ImagePath[0]" />
          <div class="detail">
            <div class="say">
              {{item.ShortDescription}}
            </div>
            <div class="user">
              <div class="userhd">
                <img v-if="item.MemberPhoto==='' || item.MemberPhoto===null" src='../../assets/img/person.png' />
                <img v-else :src='item.MemberPhoto' />
              </div>
              <div class="person">{{item.MemberName}}</div>
              <!-- @click.stop="like(item.Id)" -->
              <div class="good">
                <img src='../../assets/img/good.png' />
                <i>{{item.ZanCounts}}</i>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import MainHeader from 'components/content/MainHeader'
import { getLife, getMyLife, getMyFavoriteLife, likeLife, getFollowUsers, getLifeByUser, followUser, getIsFollow } from '../../network/life'
import { getUserDetailById } from '../../network/user'
import { copyInit } from '../../utils/share'
import { multLogin } from '../../utils/wx'

export default {
  name: 'Life',
  components: {
    MainHeader,
  },
  data(){
    return {
      loaded: false,
      userKey: localStorage.getItem('userKey'),
      userNick: localStorage.getItem('userNick'),
      userPhoto: localStorage.getItem('userPhoto'),
      isBelongMan: JSON.parse(localStorage.getItem('isBelongMan')),
      waterfallList1:[],
      waterfallList2:[],
      curIndex: 0,
      categories: ['广场', '关注' ,'我的'],
      lifeList: [],
      youISP: '',
      youBelongMan: '',
      pageNo: 1,
      pageSize: 1000,
      isFollow: false,
      isMine: false,
      Subordinate: 0, // 粉丝
      FollowCount: 0, // 关注
      FollowedCount: 0, // 被关注
      AllThemeZans: 0, // 点赞
    }
  },
  computed: {
    action(){
      return this.$route.query.action
    }
  },
  watch: {
    async action(val){
      if(val === undefined){
        await this.getLife()
      }
    }
  },
  async activated() {
    await this.getLife()
    
    if(this.action === 'you'){
      if(this.userKey){
        this.getIsFollow()
      }
    }
    // await this.getMyFavoriteLife()
    if(this.isBelongMan){
      copyInit()
    }
  },
  async mounted() {
    // 用户登录
    // let loginStatus = await multLogin(this)
    // if(!loginStatus) return false

    await this.getLife()

    if(this.action === 'you'){
      if(this.userKey){
        this.getIsFollow()
      }
    }
    // await this.getMyFavoriteLife()
    if(this.isBelongMan){
      copyInit()
    }

    // if(this.$route.query.action === 'delete'){
    //   this.itemClicked(2)
    // }
  },
  methods: {
    getIsFollow(){
      if(this.lifeList.length === 0){
        return false
      }
      let MemberId = this.lifeList[0].MemberId
      let requestData = {
        userKey: this.userKey,
        MemberId,
      }
      getIsFollow(requestData, (res) => {
        this.isFollow = res
      })
    },
    followUser(){
      let MemberId = this.lifeList[0].MemberId
      let requestData = {
        userKey: this.userKey,
        MemberId,
      }
      followUser(requestData, () => {
        // Toast('关注成功')
        this.getIsFollow()
      })
    },
    like(ThemeId){
      let requestData = {
        userkey: this.userKey,
        ThemeId,
      }
      likeLife(requestData, msg => {
        let index = this.curIndex
        if(index === 0){
          this.getLife()
        } else 
        if(index === 1){
          this.getMyFavoriteLife()
        } else 
        if(index === 2){
          this.getMyLife()
        }
      })
    },
    // 获取最新主题
    getLife(){
      return new Promise((resolve, reject) => {
        let requestData = {
          // userkey: this.userKey,
          pageIndex: this.pageNo,
          pageSize: this.pageSize,
        }
        getLife(requestData, async list => {
          // 如果从用户头像点击过来，展示用户主页
          if(this.action === 'you'){
            let userInfo = await this.getIsISPorBelong(this.$route.query.id)
            this.youISP = userInfo.IsISP
            this.youBelongMan = userInfo.IsDistributor
            // console.log(this.youISP, this.youBelongMan)
            list = list.filter(item => {
              return item.MemberId == this.$route.query.id
            })
            this.isMine = localStorage.getItem('userId') == list[0].MemberId
          }
          
          this.convertList(list)
          resolve()
        })
      })
    },
    getIsISPorBelong(userId) {
      return new Promise((resolve) => {
        getUserDetailById(userId, (userInfo) => {
          // 判断是否是城市运营商
          let isISP = userInfo.IsISP
          let isBelongMan = userInfo.IsDistributor
          this.FollowCount = userInfo.FollowCount
          this.FollowedCount = userInfo.FollowedCount
          this.AllThemeZans = userInfo.AllThemeZans
          this.Subordinate = userInfo.Subordinate
          resolve(userInfo)
        })
      })
    },
    // 获取我的主题
    getMyLife(){
      return new Promise((resolve, reject) => {
        getMyLife(list => {
          this.convertList(list)
          resolve()
        })
      })
    },
    // 获取我关注的主题
    getMyFavoriteLife(){
      return new Promise((resolve, reject) => {
        getFollowUsers(users => {
          if(users.length === 0){
            this.convertList([])
            return false
          }
          let lifeList = []
          let flag = 0
          users.map(user => {
            let memberId = user.Id
            let requestData = {
              memberId
            }
            getLifeByUser(requestData, list => {
              lifeList = [...lifeList, ...list]
              flag++
              
              if(flag >= users.length){ // 全部请求处理完后执行
                this.convertList(lifeList)
                resolve()
              }
            })
          })
          
        })
      })
    },
    convertList(list){
      list = list.reduce((pre, cur, idx) => {
        if(cur.ImagePath){
          cur.ImagePath = cur.ImagePath.split(',')
          cur.ImagePath = cur.ImagePath.map(item => {
            item = item + '?x-oss-process=image/resize,w_350/quality,q_70'
            return item
          })
          pre.push(cur)
        }
        return pre
      }, [])
      this.lifeList = list
      this.listSlice()
    },
    goToDetail(id){
      this.$router.push({
        path: '/lifeDetail',
        query: {
          id
        }
      })
    },
    async itemClicked(index){
      this.curIndex = index
      if(index === 0){
        await this.getLife()
      } else 
      if(index === 1){
        await this.getMyFavoriteLife()
      } else 
      if(index === 2){
        await this.getMyLife()

        let userId = localStorage.getItem('userId')
        getUserDetailById(userId, (userInfo) => {
          this.FollowCount = userInfo.FollowCount
          this.FollowedCount = userInfo.FollowedCount
          this.AllThemeZans = userInfo.AllThemeZans
          this.Subordinate = userInfo.Subordinate
        })
      }
    },
    //数据分列
    listSlice(){
      let list = this.lifeList
      this.waterfallList1 = []
      this.waterfallList2 = []
      for (let i = 0; i < list.length; i++){
        if(i%2 === 0){
          this.waterfallList1.push(list[i]);
        } else {
          this.waterfallList2.push(list[i]);
        }
      }
      // 动画触发
      this.loaded = true
    },
  },
}
</script>

<style scoped>
/* .container{
  display: flex;
  flex-direction: column;
  height: 100vh;
} */
.v-waterfall-content{
  flex-grow: 1;
  /* position: fixed;
  top: 150px;
  left: 10px;
  right: 10px;
  bottom: 0; */
  border-radius: 6px;
  overflow: auto;
  display: flex;
}
.item-col{
  padding: 10px 6px 10px 6px;
  width: 50%;
  box-sizing: border-box;
}
.v-waterfall-item{
  opacity: 0;
  border-radius: 5px;
  overflow: hidden;
  margin-bottom: 10px;
  background-color: #ffffff;
  transition: all ease-out 2s;
}
.v-waterfall-item img{
  width: 100%;
  height: auto;
  border-radius: 5px;
}
.v-waterfall-item .detail{
  padding: 10px;
  font-size: 12px;
}
.v-waterfall-item .detail .say{
  font-size: 12px;
  line-height: 14px;
  max-height: 42px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  word-break: break-all;
  box-sizing: border-box;
}
.v-waterfall-item .detail .user{
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 0 5px 0;
}
.v-waterfall-item .detail .user .userhd img{
  width: 20px;
  height: 20px;
  margin-right: 5px;
  border-radius: 50%;
  background-color: #f4f4f4;
  border: none;
}
.v-waterfall-item .detail .user .person{
  flex-grow: 1;
}
.v-waterfall-item .detail .user .good{
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.v-waterfall-item .detail .user .good img{
  width: 16px;
  height: 16px;
  margin-right: 5px;
}
.product-tabs{
  display: flex;
  flex-shrink: 0;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  overflow: auto;
  padding-top: 3px;
  background-color: #fff;
}
.product-tabs::-webkit-scrollbar {
  width: 0;
}
.product-tabs .tabs-list{
  display: flex;
  padding: 0 10px;
  flex-grow: 1;
}
.product-tabs .tabs-list .item{
  flex-shrink: 0;
  width: 50px;
  height: 45px;
  line-height: 42px;
  text-align: center;
  font-size: 14px;
  margin-right: 10px;
}
.product-tabs .tabs-list .item span{
  display: inline-block;
  border-bottom: 3px solid #ffffff;
}
.product-tabs .tabs-list .item-cur span{
  color: #d50721;
  border-bottom: 3px solid #d50721;
}
.product-tabs .pub{
  line-height: 45px;
  padding-right: 30px;
  padding-left: 10px;
  font-size: 14px;
  font-weight: bold;
}
.me{
  flex-grow: 0;
  flex-shrink: 0;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 15px;
  border-radius: 4px;
  background-color: #fff;
  margin: 10px 6px 2px 6px;
  box-shadow: 0 3px 3px rgba(0, 0, 0, .1);
}
.me .avatar{
  width: 42px;
  height: 42px;
  border-radius: 50%;
  margin-right: 15px;
}
.me .user-info{
  flex-grow: 1;
  font-size: 12px;
  line-height: 1.5;
}
.me .user-info .name em{
  font-size: 16px;
  margin-right: 15px;
}
.me .user-info .counts span{
  padding-right: 15px;
  color: #999;
}
.me .share img{
  width: 16px;
}
.share-loading{
  position: absolute;
  top: 50%;
  left: 50%;
  width: 60px;
  height: 60px;
  margin: -130px 0 0 -30px;
  opacity: .2;
  animation: rotate 3s linear infinite;
}
@keyframes rotate{
  from{transform: rotate(0deg)}
  to{transform: rotate(360deg)}
}
.concern img{
  width: 22px;
  padding: 10px;
}
.concern span{
  display: inline-block;
  color: #999;
  font-size: 14px;
  padding: 10px;
}
</style>
